import SwiftUI
import CoreLocation

struct AppleGeocodingTestView: View {
    @State private var testResults: [String] = []
    @State private var isLoading = false
    @EnvironmentObject var photoService: PhotoService
    
    // 测试坐标
    private let testCoordinates = [
        ("北京天安门", CLLocationCoordinate2D(latitude: 39.9042, longitude: 116.4074)),
        ("上海外滩", CLLocationCoordinate2D(latitude: 31.2304, longitude: 121.4737)),
        ("广州塔", CLLocationCoordinate2D(latitude: 23.1066, longitude: 113.3213)),
        ("深圳世界之窗", CLLocationCoordinate2D(latitude: 22.5405, longitude: 113.9344)),
        ("杭州西湖", CLLocationCoordinate2D(latitude: 30.2741, longitude: 120.1551))
    ]
    
    var body: some View {
        NavigationView {
            VStack(spacing: 16) {
                // 标题
                Text("AppleGeocodingService 测试")
                    .font(.title2)
                    .fontWeight(.bold)
                    .padding(.top)
                
                // 测试按钮
                VStack(spacing: 12) {
                    Button("测试当前配置的地理编码") {
                        testCurrentConfiguration()
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.purple)
                    
                    Button("测试PhotoService中的AppleGeocodingService") {
                        testPhotoServiceAppleGeocoding()
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.orange)
                    
                    Button("测试单个坐标") {
                        testSingleCoordinate()
                    }
                    .buttonStyle(.borderedProminent)
                    
                    Button("测试所有坐标") {
                        testAllCoordinates()
                    }
                    .buttonStyle(.borderedProminent)
                    
                    Button("测试逆地理编码") {
                        testReverseGeocoding()
                    }
                    .buttonStyle(.borderedProminent)
                    
                    Button("清空结果") {
                        testResults.removeAll()
                    }
                    .buttonStyle(.bordered)
                }
                .padding()
                
                // 加载指示器
                if isLoading {
                    ProgressView("测试中...")
                        .padding()
                }
                
                // 结果显示
                ScrollView {
                    LazyVStack(alignment: .leading, spacing: 8) {
                        ForEach(testResults, id: \.self) { result in
                            Text(result)
                                .font(.system(.caption, design: .monospaced))
                                .padding(8)
                                .background(Color(.systemGray6))
                                .cornerRadius(6)
                        }
                    }
                    .padding()
                }
                
                Spacer()
            }
            .navigationTitle("地理编码测试")
        }
    }
    
    private func testCurrentConfiguration() {
        isLoading = true
        
        Task {
            let config = GeocodingConfig.shared
            addResult("🧪 === 开始测试当前地理编码配置 ===")
            addResult("")
            
            let validation = config.validateConfig()
            addResult("📋 配置状态: " + (validation ? "有效" : "无效"))
            
            let availableServices = config.getAvailableServices()
            addResult("📋 可用服务: \(availableServices.map { $0.displayName }.joined(separator: " → "))")
            addResult("")
            
            // 测试一个坐标
            let testCoordinate = CLLocationCoordinate2D(latitude: 39.9042, longitude: 116.4074)
            addResult("📍 测试坐标: 北京天安门 (39.9042, 116.4074)")
            
            if let result = await photoService.testGeocodingWithCurrentConfig(coordinate: testCoordinate) {
                addResult("✅ 地理编码成功!")
                addResult("🏠 地址: \(result.address ?? "未知")")
                addResult("🏙️ 城市: \(result.city ?? "未知")")
                addResult("🌍 国家: \(result.country ?? "未知")")
            } else {
                addResult("❌ 地理编码失败")
            }
            
            addResult("")
            addResult("🧪 === 当前配置测试完成 ===")
            addResult("📝 请查看Xcode控制台日志获取详细结果")
            
            await MainActor.run {
                isLoading = false
            }
        }
    }
    
    private func testPhotoServiceAppleGeocoding() {
        isLoading = true
        
        Task {
            addResult("🧪 === 开始测试PhotoService中的AppleGeocodingService ===")
            addResult("")
            
            await photoService.testAppleGeocodingService()
            
            addResult("🧪 === PhotoService中的AppleGeocodingService测试完成 ===")
            addResult("📝 请查看Xcode控制台日志获取详细结果")
            
            await MainActor.run {
                isLoading = false
            }
        }
    }
    
    private func testSingleCoordinate() {
        isLoading = true
        let coordinate = testCoordinates[0]
        
        Task {
            let startTime = Date()
            addResult("🟢 开始测试单个坐标: \(coordinate.0)")
            
            do {
                let result = await AppleGeocodingService.shared.fetchAddressInfoAsync(
                    latitude: coordinate.1.latitude,
                    longitude: coordinate.1.longitude
                )
                let endTime = Date()
                let duration = endTime.timeIntervalSince(startTime)
                
                if let result = result {
                    addResult("✅ 测试成功 - \(coordinate.0)")
                    addResult("📍 坐标: \(coordinate.1.latitude), \(coordinate.1.longitude)")
                    addResult("🏠 地址: \(result.displayName)")
                    addResult("🏙️ 城市: \(result.cityName)")
                    addResult("🌍 国家: \(result.countryName)")
                    addResult("⏱️ 耗时: \(String(format: "%.3f", duration))秒")
                    addResult("")
                } else {
                    addResult("❌ 测试失败 - \(coordinate.0)")
                    addResult("📍 坐标: \(coordinate.1.latitude), \(coordinate.1.longitude)")
                    addResult("🚨 错误: 未获取到地址信息")
                    addResult("⏱️ 耗时: \(String(format: "%.3f", duration))秒")
                    addResult("")
                }
                
            } catch {
                let endTime = Date()
                let duration = endTime.timeIntervalSince(startTime)
                
                addResult("❌ 测试失败 - \(coordinate.0)")
                addResult("📍 坐标: \(coordinate.1.latitude), \(coordinate.1.longitude)")
                addResult("🚨 错误: \(error.localizedDescription)")
                addResult("⏱️ 耗时: \(String(format: "%.3f", duration))秒")
                addResult("")
            }
            
            await MainActor.run {
                isLoading = false
            }
        }
    }
    
    private func testAllCoordinates() {
        isLoading = true
        
        Task {
            addResult("🟢 开始测试所有坐标...")
            addResult("")
            
            for (index, coordinate) in testCoordinates.enumerated() {
                let startTime = Date()
                addResult("📋 测试 \(index + 1)/\(testCoordinates.count): \(coordinate.0)")
                
                do {
                    let result = await AppleGeocodingService.shared.fetchAddressInfoAsync(
                        latitude: coordinate.1.latitude,
                        longitude: coordinate.1.longitude
                    )
                    let endTime = Date()
                    let duration = endTime.timeIntervalSince(startTime)
                    
                    if let result = result {
                        addResult("✅ \(coordinate.0): \(result.displayName)")
                        addResult("⏱️ 耗时: \(String(format: "%.3f", duration))秒")
                    } else {
                        addResult("❌ \(coordinate.0): 未获取到地址信息")
                        addResult("⏱️ 耗时: \(String(format: "%.3f", duration))秒")
                    }
                    
                } catch {
                    let endTime = Date()
                    let duration = endTime.timeIntervalSince(startTime)
                    
                    addResult("❌ \(coordinate.0): \(error.localizedDescription)")
                    addResult("⏱️ 耗时: \(String(format: "%.3f", duration))秒")
                }
                
                addResult("")
                
                // 添加小延迟避免过快请求
                try? await Task.sleep(nanoseconds: 500_000_000) // 0.5秒
            }
            
            addResult("🎉 所有测试完成!")
            
            await MainActor.run {
                isLoading = false
            }
        }
    }
    
    private func testReverseGeocoding() {
        isLoading = true
        
        Task {
            addResult("🟢 开始测试逆地理编码...")
            addResult("")
            
            // 测试一些随机坐标
            let randomCoordinates = [
                CLLocationCoordinate2D(latitude: 39.9042, longitude: 116.4074), // 北京
                CLLocationCoordinate2D(latitude: 31.2304, longitude: 121.4737), // 上海
                CLLocationCoordinate2D(latitude: 22.3193, longitude: 114.1694), // 香港
                CLLocationCoordinate2D(latitude: 25.0330, longitude: 121.5654), // 台北
                CLLocationCoordinate2D(latitude: 35.6762, longitude: 139.6503)  // 东京
            ]
            
            for (index, coordinate) in randomCoordinates.enumerated() {
                let startTime = Date()
                addResult("📋 逆地理编码测试 \(index + 1)/\(randomCoordinates.count)")
                addResult("📍 坐标: \(coordinate.latitude), \(coordinate.longitude)")
                
                do {
                    let result = await AppleGeocodingService.shared.fetchAddressInfoAsync(
                        latitude: coordinate.latitude,
                        longitude: coordinate.longitude
                    )
                    let endTime = Date()
                    let duration = endTime.timeIntervalSince(startTime)
                    
                    if let result = result {
                        addResult("✅ 结果: \(result.displayName)")
                        addResult("🏙️ 城市: \(result.cityName)")
                        addResult("🌍 国家: \(result.countryName)")
                        addResult("⏱️ 耗时: \(String(format: "%.3f", duration))秒")
                    } else {
                        addResult("❌ 错误: 未获取到地址信息")
                        addResult("⏱️ 耗时: \(String(format: "%.3f", duration))秒")
                    }
                    
                } catch {
                    let endTime = Date()
                    let duration = endTime.timeIntervalSince(startTime)
                    
                    addResult("❌ 错误: \(error.localizedDescription)")
                    addResult("⏱️ 耗时: \(String(format: "%.3f", duration))秒")
                }
                
                addResult("")
                
                // 添加小延迟
                try? await Task.sleep(nanoseconds: 500_000_000)
            }
            
            addResult("🎉 逆地理编码测试完成!")
            
            await MainActor.run {
                isLoading = false
            }
        }
    }
    
    private func addResult(_ message: String) {
        DispatchQueue.main.async {
            let timestamp = DateFormatter().apply {
                $0.dateFormat = "HH:mm:ss.SSS"
            }.string(from: Date())
            
            testResults.append("[\(timestamp)] \(message)")
        }
    }
}

#Preview {
    AppleGeocodingTestView()
}

// MARK: - 扩展
extension DateFormatter {
    func apply(_ block: (DateFormatter) -> Void) -> DateFormatter {
        block(self)
        return self
    }
}
